世界上真正有價值的事物,需要熱情和犧牲才能完成。鐵人賽就是耶!
大家好今天我要來示範個容易上手的功能optionsMenu,optionsMenu選項選單在app畫面中的右上角標題列有一個可以點選的按鈕(通常叫做menu鍵),當使用者點下menu鍵後會彈出選項來讓使用者選取,當然還有其他類似的功能像是SubMenu和ContextMenu,我們以後有機會在介紹他們兩個,廢話不多說那我就開始示範吧!
一樣先上程式碼
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
在佈局方面我單純給他一個簡單的ImageView待會會使用到
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
final private int north_america = 0;
final private int south_america = 1;
final private int asia = 2;
final private int europe = 3;
final private int africa = 4;
final private int oceania = 5;
final private int antarctica = 6;
String [] continent = {"北美洲","南美洲","亞洲","歐洲","非洲","大洋洲","南極洲"};
int[] continent_image = {R.drawable.north_america,R.drawable.south_america,R.drawable.asia,R.drawable.europe
,R.drawable.africa,R.drawable.oceania,R.drawable.antarctica
};
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1, north_america,1,"北美洲");
menu.add(1, south_america,2,"南美洲");
menu.add(1, asia,3,"亞洲");
menu.add(1, europe,4,"歐洲");
menu.add(1, africa,5,"非洲");
menu.add(1, oceania,6,"大洋洲");
menu.add(1, antarctica,7,"南極洲");
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case north_america:
mImageView.setImageResource(continent_image[0]);
break;
case south_america:
mImageView.setImageResource(continent_image[1]);
break;
case asia:
mImageView.setImageResource(continent_image[2]);
break;
case europe:
mImageView.setImageResource(continent_image[3]);
break;
case africa:
mImageView.setImageResource(continent_image[4]);
break;
case oceania:
mImageView.setImageResource(continent_image[5]);
break;
case antarctica:
mImageView.setImageResource(continent_image[6]);
break;
}
return super.onOptionsItemSelected(item);
}
}
我來介紹一下選項選單使用到的方法:
onCreateOptionsMenu 在這裡是完成menu的初始化。
onOptionsItemSelected 當menu裡面的選單選中時觸發下一步動作
這樣就完成一個簡單的選項選單了,那今天的示範就到這了,謝謝大家的觀看。